import 'package:jingyuan/commmon/LocalStorage.dart';

class FavoriteMgr {
  FavoriteMgr._internal();

  static FavoriteMgr? _instance;
  static const String _cfgKey = "favorite_cfg";
  static List<dynamic> _datas = [0, 500, 972, 1307, 1464, 1636, 1772, 1865, 1889, 2000, 2568];

  static FavoriteMgr getInstance() {
    _instance ??= FavoriteMgr._internal();
    return _instance!;
  }

  initMgr() async {
    var cfg = await LocalStorage.getJson(_cfgKey);
    if (cfg != null) {
      _datas = cfg;
    }
  }

  factory FavoriteMgr() => getInstance();

  add(int index) {
    if (!isItemIn(index)) {
      bool saved = false;
      for (int i = 0; i < _datas.length; ++i) {
        if (_datas[i] > index) {
          _datas.insert(i, index);
          saved = true;
          break;
        }
      }
      if (!saved) {
        _datas.add(index);
      }
      _save();
    }
  }

  remove(int index) {
    if (_datas.remove(index)) {
      _save();
    }
  }

  isItemIn(int index) {
    return _datas.contains(index);
  }

  int getItemByIndex(int index) {
    if (index < 0 || index >= _datas.length) return -1;
    return _datas[index];
  }

  size() {
    return _datas.length;
  }

  _save() {
    LocalStorage.setJson(_cfgKey, _datas);
  }
}
